package org.example.datasource;
import java.util.Map;
import java.util.regex.Pattern;

public class DynamicSqlBuilder {

    public String buildQuerySql(Map<String, Object> params) {
        String rawSql = (String) params.get("rawSql");

        // SQL安全验证（只允许SELECT查询）
        if (!isSafeQuery(rawSql)) {
            throw new SecurityException("非法SQL操作");
        }

        return rawSql;
    }

    private boolean isSafeQuery(String sql) {
        // 转换为小写简化检查
        String cleanSql = sql.toLowerCase().replaceAll("\\s+", " ");

        // 禁止DDL操作关键字
        Pattern ddlPattern = Pattern.compile(
                "(alter|create|drop|rename|truncate|comment|grant|revoke)"
        );
        if (ddlPattern.matcher(cleanSql).find()) {
            return false;
        }

        // 禁止写操作
        Pattern dmlPattern = Pattern.compile(
                "(insert|update|delete|merge|replace|lock)"
        );
        if (dmlPattern.matcher(cleanSql).find()) {
            return false;
        }

        // 允许SELECT查询
        return cleanSql.startsWith("select") || cleanSql.startsWith("show") || cleanSql.startsWith("describe");
    }

}
